package com.feihong.txgw.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.feihong.txgw.R;

import java.io.File;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @name txgw_app
 * @class name：com.feihong.txgw.utils
 * @class describe:
 * @author wangziheng
 * @time 2017/10/26 16:14
 * @change
 * @chang time
 * @class describe
 */
public class ChooseMapHelper {

    private Activity context;
    private List<String> mPosition;

    public ChooseMapHelper(Activity context, List<String> mData) {
        this.context = context;
        this.mPosition = mData;
    }

    private View popView;
    private PopupWindow popWindow;

    private String title;


    public void showPop(View showViewId,String title) {
        this.title = title;
        LayoutInflater inflate = LayoutInflater.from(context);
        popView = inflate.inflate(R.layout.user_change_sex, null, false);

//        TextView gaoMapBtn = (TextView) popView.findViewById(R.id.dialog_Title_top_tv);
//        gaoMapBtn.setVisibility(View.VISIBLE);
        TextView baiduMapBtn = (TextView) popView.findViewById(R.id.dialog_Title_tv);
        TextView tencentMapBtn = (TextView) popView.findViewById(R.id.dialog_Content_tv);
        TextView cancleBtn = (TextView) popView.findViewById(R.id.dialog_cannel_tv);

        popWindow = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT, false);
        popWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        // 需要设置一下此参数，点击外边可消失
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置点击窗口外边窗口消失
        popWindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        popWindow.setFocusable(true);
        popWindow.setTouchable(true);
        popWindow.update();
        popWindow.showAtLocation(showViewId, Gravity.CENTER, 0, 0);
        popView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popView.isShown()) {
                    popWindow.dismiss();
                }
            }
        });
//        gaoMapBtn.setOnClickListener(cameraListener);
        baiduMapBtn.setOnClickListener(cameraListener);
        tencentMapBtn.setOnClickListener(cameraListener);
        cancleBtn.setOnClickListener(cameraListener);

        if(!isInstallByread("com.baidu.BaiduMap")){
            baiduMapBtn.setText("百度地图(未安装)");
        }else {
            baiduMapBtn.setText("百度地图");
        }

        if(!isInstallByread("com.autonavi.minimap")){
//            gaoMapBtn.setText("高德地图(未安装)");
        }else {
            baiduMapBtn.setText("高德地图");
        }

        if(!isInstallByread("com.tencent.map")){
            tencentMapBtn.setText("腾讯地图(未安装)");
        }else {
            baiduMapBtn.setText("高德地图");
        }

    }

    private View.OnClickListener cameraListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
//                case R.id.dialog_Title_top_tv:
//                    selectGaode(title);
//                    break;
                case R.id.dialog_Title_tv:
                    selectBaidu(title);
                    break;
                case R.id.dialog_Content_tv:
                    selectTencent(title);
                    break;
                case R.id.dialog_cannel_tv:
                    if (popView != null && popView.isShown()) {
                        popWindow.dismiss();
                    }
                    break;
                    default:break;
            }
            if (popView != null && popView.isShown()) {
                popWindow.dismiss();
            }
        }
    };

    private void selectBaidu(String title) {
        try {
            //调起App
            if (isInstallByread("com.baidu.BaiduMap")) {
                double[] locationDes =  gaoDeToBaidu(Double.parseDouble(mPosition.get(2)),Double.parseDouble(mPosition.get(3)));
                Intent intent = Intent.getIntent("intent://map/direction?" +
                        //"origin=latlng:"+"34.264642646862,108.95108518068&" +   //起点  此处不传值默认选择当前位置
                        "destination=latlng:"+locationDes[0]+","+locationDes[1]+"|name:目的地"+        //终点
                        "&mode=drivingreferer=Autohome|GasStation#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                context.startActivity(intent);
            } else {
                Toast.makeText(context, "您还没有安装百度地图APP",Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void selectGaode(String title) {
        if (isInstallByread("com.autonavi.minimap")) {
            try {
                Intent intentOther = new Intent("android.intent.action.VIEW",
                        Uri.parse("amapuri://route/plan/?sid=BGVIS1&sname=我的位置&did=BGVIS2&dlat="+mPosition.get(2)+
                                "&dlon="+mPosition.get(3)+"&dname=目的地&dev=0&t=1")//跳转至路径规划
                        /*Uri.parse("androidamap://navi?sourceApplication=e游客&poiname=我的目的地&lat="
                                + mPosition.get(2) + "&lon=" +  mPosition.get(3) + "&dev=0&style=2")//直接跳转至导航*/);
                intentOther.addCategory("android.intent.category.DEFAULT");
                intentOther.setPackage("com.autonavi.minimap");
                intentOther.setAction("android.intent.action.VIEW");
                intentOther.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(intentOther);
            } catch (Exception e) {
                Toast.makeText(context,"您还没有安装高德地图APP",Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context,"您还没有安装高德地图APP",Toast.LENGTH_SHORT).show();
        }
    }


    private void selectTencent(String title) {

        /*try {
            StringBuffer sb = new StringBuffer();
            sb.append("geo:").append(mPosition.get(2)).append(",").append(mPosition.get(3))
                    .append("?").append("z=").append(14).append("?").append("q=")
                    .append(mPosition.get(4));
            Uri mUri = Uri.parse(sb.toString());
            Intent mIntent = new Intent(Intent.ACTION_VIEW, mUri);
            context.startActivity(mIntent);
        } catch (Exception e) {
            ToastHelper.showToast(context,"您还没有安装腾讯地图APP");
        }*/


        if(isInstallByread("com.tencent.map")){
            try {
                String URL = "qqmap://map/routeplan?type=drive&" +
                        "from=我的位置&fromcoord="+mPosition.get(0)+","+mPosition.get(1)+"&to="+title+"&" +
                        "tocoord="+mPosition.get(2)+","+mPosition.get(3)+"&policy=1&referer="+context.getResources().getString(R.string.app_name);
                Intent intent = Intent.parseUri(URL, 0);

                intent.setComponent(null);
                intent.setSelector(null);
                context.startActivity(intent);
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(context,"启动地图失败",Toast.LENGTH_SHORT).show();
                return;
            }
        }else{
            Toast.makeText(context,"您还没有安装腾讯地图APP",Toast.LENGTH_SHORT).show();
        }
    }


    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    public double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }
}
